//
//  DJIRootViewController.m
//  UILibOCSample
//
//  Created by apple on 2018/3/16.
//  Copyright © 2018年 DJI. All rights reserved.
//

#import "DJIRootViewController.h"
#import <DJISDK/DJISDK.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
#import "DemoUtility.h"
#import "DJIWaypointConfigViewController.h"
#import "BaseWebViewVC.h"
#import "LinePointsModel.h"
#import "LineMkPolygon.h"
#import "AirCraftVC.h"

//拍照
#import "DemoUtility.h"
#import <VideoPreviewer/VideoPreviewer.h>
#import "VideoPreviewerSDKAdapter.h"
#import "CameraShootSinglePhotoViewController.h"
@interface DJIRootViewController ()<DJIGSButtonViewControllerDelegate,MKMapViewDelegate,CLLocationManagerDelegate,DJISDKManagerDelegate, DJIFlightControllerDelegate,DJIWaypointConfigViewControllerDelegate,DJICameraDelegate,UITextFieldDelegate,UIGestureRecognizerDelegate>
/** map*/
@property (nonatomic, strong) MKMapView *mapView;
@property (nonatomic, assign) BOOL isEditingPoints;
@property (nonatomic, strong) DJIGSButtonViewController *gsButtonVC;
@property (nonatomic, strong) DJIWaypointConfigViewController *waypointConfigVC;
@property (nonatomic, strong) CLLocationManager* locationManager;
@property (nonatomic, assign) CLLocationCoordinate2D userLocation;

@property(nonatomic, strong)  UILabel* modeLabel;
@property(nonatomic, strong)  UILabel* gpsLabel;
@property(nonatomic, strong)  UILabel* hsLabel;
@property(nonatomic, strong)  UILabel* vsLabel;
@property(nonatomic, strong)  UILabel* altitudeLabel;
@property(nonatomic, assign)  CLLocationCoordinate2D droneLocation;
@property (nonatomic, strong) NSArray *polygons;
@property (nonatomic, strong) NSArray *lines;
@property(nonatomic, strong) DJIMutableWaypointMission* waypointMission;
/** 图片预览视图*/
//@property (nonatomic, strong) UIView *menbanPhotoView;
//@property (strong, nonatomic) UIView *videoFeedView;
@property (strong, nonatomic) UIButton *shootPhotoButton;
@property (nonatomic) BOOL isInShootPhotoMode;
@property (nonatomic) BOOL isShootingPhoto;
@property (nonatomic) BOOL isStoringPhoto;
@property (strong, nonatomic) UIView *videoFeedView;
@property (nonatomic) VideoPreviewerSDKAdapter *previewerAdapter;
@property (nonatomic, strong) CameraShootSinglePhotoViewController *cameraVC;

@property (strong, nonatomic) DULStatusBarViewController *statusBarVC;
@property (strong, nonatomic) DULPreflightChecklistController *checkListVC;
@property (strong, nonatomic) UIView *statusBarContainingView;

/** 飞行航线参数点*/
@property (nonatomic, strong) NSMutableArray *flyPointsDataArr;
/** 修改飞行高度*/
@property (nonatomic, strong) UITextField *setFlyHeightTextField;
//定义一个进度条属性
@property(retain,nonatomic) UIProgressView * progressView;
//sideOverLay定义滑动条属性
@property(retain,nonatomic) UISlider *slider;
//frontOverLay滑动条
@property (retain, nonatomic) UISlider *frontOverLay;
//飞行速度
@property (retain, nonatomic) UISlider *flySpeed;
@end

@implementation DJIRootViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [self startUpdateLocation];

    [self setVideoPreview];
  
    __weak DJICamera* camera = [DemoComponentHelper fetchCamera];
    if (camera) {
        [camera setDelegate:self];
    }

    [self getCameraMode];
}

/**
 *飞行器距离出发点距离
 */
- (void)createDisView {
    //大的背景视图
    UIView  *disView = [[UIView alloc] initWithFrame:CGRectMake(20,SCREEN_HEIGHT -70, SCREEN_WIDTH/2, 70)];
    disView.hidden = YES;
    disView.backgroundColor = [UIColor whiteColor];
    [self.mapView addSubview:disView];
    //飞行器离出发地距离
    UILabel *airCraftLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, disView.frame.size.width/2, disView.frame.size.height)];
    airCraftLab.textColor = [UIColor blackColor];
    [disView addSubview:airCraftLab];
    //总距离
    UILabel *totalDisLab = [[UILabel alloc] initWithFrame:CGRectMake(airCraftLab.frame.size.width, 0, disView.frame.size.width/2, disView.frame.size.height)];
    
    totalDisLab.textColor = [UIColor blueColor];
    [disView addSubview:totalDisLab];
    
    //值回调
    self.mapController.sDisAndTotalDisBlock = ^(NSString *sDis, NSString *totalDis) {
        disView.hidden = NO;
        airCraftLab.text = [NSString stringWithFormat:@"拍摄间隔:%@s",sDis];
        totalDisLab.text = [NSString stringWithFormat:@"飞行总时间%@s",totalDis];
    };
    
}

#pragma mark - Precondition
/**
 *  Check if the camera's mode is DJICameraModeShootPhoto.
 *  If the mode is not DJICameraModeShootPhoto, we need to set it to be ShootPhoto.
 *  If the mode is already DJICameraModeShootPhoto, we check the exposure mode.
 */
-(void) getCameraMode {
    __weak DJICamera* camera = [DemoComponentHelper fetchCamera];
    if (camera) {
        WeakRef(target);
        [camera getModeWithCompletion:^(DJICameraMode mode, NSError * _Nullable error) {
            WeakReturn(target);
            if (error) {
                ShowResult(@"ERROR: getModeWithCompletion:. %@", error.description);
            }
            else if (mode == DJICameraModeShootPhoto) {
                target.isInShootPhotoMode = YES;
            }
            else {
                [target setCameraMode];
            }
        }];
    }
}

/**
 *  Set the camera's mode to DJICameraModeShootPhoto.
 *  If it succeeds, we can enable the take photo button.
 */
-(void) setCameraMode {
    __weak DJICamera* camera = [DemoComponentHelper fetchCamera];
    if (camera) {
        WeakRef(target);
        [camera setMode:DJICameraModeShootPhoto withCompletion:^(NSError * _Nullable error) {
            WeakReturn(target);
            if (error) {
                ShowResult(@"ERROR: setMode:withCompletion:. %@", error.description);
            }
            else {
                // Normally, once an operation is finished, the camera still needs some time to finish up
                // all the work. It is safe to delay the next operation after an operation is finished.
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    WeakReturn(target);
                    [camera setShootPhotoMode:DJICameraShootPhotoModeSingle withCompletion:^(NSError * _Nullable error) {
                        WeakReturn(target);
                        if (error) {
                            ShowResult(@"ERROR: setShootPhotoMode:withCompletion:. %@", error.description);
                        }
                        else {
                            target.isInShootPhotoMode = YES;
                        }
                    }];
                });
            }
        }];
    }
}

- (void)takePhoto {
    [self getCameraMode];
    __weak DJICamera* camera = [DemoComponentHelper fetchCamera];
    if (camera) {
        [self.shootPhotoButton setEnabled:NO];
        [camera startShootPhotoWithCompletion:^(NSError * _Nullable error) {
            if (error) {
                ShowResult(@"ERROR: startShootPhoto:withCompletion:. %@", error.description);
            }
        }];
    }
}

#pragma mark - UI related
- (void)setVideoPreview {
    self.videoFeedView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - SCREEN_WIDTH/4,SCREEN_HEIGHT - SCREEN_HEIGHT/4, SCREEN_WIDTH/4, SCREEN_HEIGHT/4)];
    [self.view addSubview:self.videoFeedView];
    [self.view insertSubview:self.videoFeedView aboveSubview:self.mapView];
    
    [[VideoPreviewer instance] start];
    [[VideoPreviewer instance] setView:self.videoFeedView];
    self.previewerAdapter = [VideoPreviewerSDKAdapter adapterWithDefaultSettings];
    [self.previewerAdapter start];
}

- (void)cleanVideoPreview {
    [[VideoPreviewer instance] unSetView];
    if (self.previewerAdapter) {
        [self.previewerAdapter stop];
        self.previewerAdapter = nil;
    }
}

-(void) setIsInShootPhotoMode:(BOOL)isInShootPhotoMode {
    _isInShootPhotoMode = isInShootPhotoMode;
    [self toggleShootPhotoButton];
}

-(void) setIsShootingPhoto:(BOOL)isShootingPhoto {
    _isShootingPhoto = isShootingPhoto;
    [self toggleShootPhotoButton];
}

-(void) setIsStoringPhoto:(BOOL)isStoringPhoto {
    _isStoringPhoto = isStoringPhoto;
    [self toggleShootPhotoButton];
}

-(void) toggleShootPhotoButton {
    [self.shootPhotoButton setEnabled:(self.isInShootPhotoMode && !self.isShootingPhoto && !self.isStoringPhoto)];
}

#pragma mark - DJICameraDelegate
-(void)camera:(DJICamera *)camera didReceiveVideoData:(uint8_t *)videoBuffer length:(size_t)length {
    [ToolHelper notifyError:[NSString stringWithFormat:@"%s---%zu",videoBuffer,length]];
    [[VideoPreviewer instance] push:videoBuffer length:(int)length];
}

-(void)camera:(DJICamera *)camera didUpdateSystemState:(DJICameraSystemState *)systemState {
    self.isShootingPhoto = systemState.isShootingSinglePhoto ||
    systemState.isShootingIntervalPhoto ||
    systemState.isShootingBurstPhoto;
    
    self.isStoringPhoto = systemState.isStoringPhoto;
}

- (void)camera:(DJICamera *_Nonnull)camera didGenerateNewMediaFile:(DJIMediaFile *_Nonnull)newMedia {
    [ToolHelper notifyError:[NSString stringWithFormat:@"获取到新图片--地址:%@",newMedia]];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.locationManager stopUpdatingLocation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.flyPointsDataArr = [NSMutableArray array];
    
    
    [self registerApp];
    [self initSubUI];
    [self initUI];
    [self initPhotoUI];
    [self createDisView];
    _cameraVC = [[CameraShootSinglePhotoViewController alloc] init];
    _cameraVC.view.frame = CGRectMake(SCREEN_WIDTH - SCREEN_WIDTH/4 - 50,SCREEN_HEIGHT - SCREEN_HEIGHT / 4.4 , SCREEN_WIDTH/4,SCREEN_HEIGHT/4.4);

    [self addChildViewController:_cameraVC];
    [self.view addSubview:_cameraVC.view];

}

#pragma mark - Actions
/**
 *  When the pre-condition meets, the shoot photo button should be enabled. Then the user can can shoot
 *  a photo now.
 */
- (void)onShootPhotoButtonClicked:(id)sender {
   [self takePhoto];
}



#pragma mark - 与拍照相关视图 在VideoPreviewer 上覆盖一层蒙版视图，添加tap手势，切换地图 和 图片预览
- (void)initPhotoUI {
    //拍照按钮
    _shootPhotoButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 70, (SCREEN_HEIGHT - 50 ) / 2, 50, 50)];
    [_shootPhotoButton setTitle:@"拍照" forState:0];
    _shootPhotoButton.layer.cornerRadius = 25;
    [_shootPhotoButton setTitleColor:[UIColor redColor] forState:0];

    [_shootPhotoButton setBackgroundColor:[UIColor blackColor]];
    [_shootPhotoButton addTarget:self action:@selector(onShootPhotoButtonClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.mapView addSubview:_shootPhotoButton];
//
//
//    //蒙板
//    self.menbanPhotoView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - SCREEN_WIDTH / 4, SCREEN_HEIGHT - SCREEN_HEIGHT / 4, SCREEN_WIDTH / 4, SCREEN_HEIGHT / 4)];
//    self.menbanPhotoView.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.f];
//    [self.mapView
//      addSubview:self.menbanPhotoView];
}


- (void)registerApp
{
    //Please enter your App key in the info.plist file to register the app.
    [DJISDKManager registerAppWithDelegate:self];
}

- (void)initSubUI {
    self.mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.mapView.delegate = self;
    self.mapView.rotateEnabled = NO;
    self.mapView.mapType = MKMapTypeSatellite;
    [self.view addSubview:self.mapView];
    
    self.userLocation = kCLLocationCoordinate2DInvalid;
    self.mapController = [[DJIMapController alloc] init];
    self.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addWaypoints:)];
    [self.mapView addGestureRecognizer:self.tapGesture];

    @WeakObj(self);
    //拍照
    self.mapController.takePhotoBlock = ^{
        [selfWeak takePhoto];
    };
    
    //上方飞行器状态视图
    //1.bg视图
    UIView *airCraftStateView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 64)];
    airCraftStateView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.65];
    [self.mapView addSubview:airCraftStateView];
    //1.1给个按钮的宽高
    CGFloat eachLabW = SCREEN_WIDTH / 5;
    CGFloat eachLabH = 40;
    
    self.modeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 12, eachLabW, eachLabH)];
    self.modeLabel.textColor = [UIColor whiteColor];
    self.modeLabel.textAlignment = NSTextAlignmentCenter;
    [airCraftStateView addSubview:self.modeLabel];
    
    self.gpsLabel = [[UILabel alloc] initWithFrame:CGRectMake(eachLabW, 12, eachLabW, eachLabH)];
    self.gpsLabel.textColor = [UIColor whiteColor];
    self.gpsLabel.textAlignment = NSTextAlignmentCenter;
    [airCraftStateView addSubview:self.gpsLabel];
    
    self.hsLabel = [[UILabel alloc] initWithFrame:CGRectMake(eachLabW * 2, 12, eachLabW, eachLabH)];
    self.hsLabel.textColor = [UIColor whiteColor];
    self.hsLabel.textAlignment = NSTextAlignmentCenter;
    [airCraftStateView addSubview:self.hsLabel];
    
    self.vsLabel = [[UILabel alloc] initWithFrame:CGRectMake(eachLabW * 3, 12, eachLabW, eachLabH)];
    self.vsLabel.textColor = [UIColor whiteColor];
    self.vsLabel.textAlignment = NSTextAlignmentCenter;
    [airCraftStateView addSubview:self.vsLabel];
    
    self.altitudeLabel = [[UILabel alloc] initWithFrame:CGRectMake(eachLabW * 4, 12, eachLabW, eachLabH)];
    self.altitudeLabel.textColor = [UIColor whiteColor];
    self.altitudeLabel.textAlignment = NSTextAlignmentCenter;
    [airCraftStateView addSubview:self.altitudeLabel];
    
    //GSBTN
    self.gsButtonVC = [[DJIGSButtonViewController alloc] initWithNibName:@"DJIGSButtonViewController" bundle:[NSBundle mainBundle]];
    [self.gsButtonVC.view setFrame:CGRectMake(0, 200, 100, 600)];
    self.gsButtonVC.delegate = self;
    [self.view addSubview:self.gsButtonVC.view];
    
    //配置视图
    self.waypointConfigVC = [[DJIWaypointConfigViewController alloc] initWithNibName:@"DJIWaypointConfigViewController" bundle:[NSBundle mainBundle]];
    self.waypointConfigVC.view.alpha = 0;
    
    self.waypointConfigVC.view.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
    
    CGFloat configVCOriginX = (CGRectGetWidth(self.view.frame) - CGRectGetWidth(self.waypointConfigVC.view.frame))/2;
    CGFloat configVCOriginY = 64;
    
    [self.waypointConfigVC.view setFrame:CGRectMake(configVCOriginX, configVCOriginY, CGRectGetWidth(self.waypointConfigVC.view.frame), CGRectGetHeight(self.waypointConfigVC.view.frame))];
    
    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) //Check if it's using iPad and center the config view
    {
        self.waypointConfigVC.view.center = self.view.center;
    }
    self.waypointConfigVC.delegate = self;
    [self.view addSubview:self.waypointConfigVC.view];

    
    //创建滑动条对象(sideOverLay)
    _slider = [[UISlider alloc]init];
    //位置设置，高度不可变更，40写的不起作用，系统默认
    _slider.frame =CGRectMake(SCREEN_WIDTH - 350,100, 300, 40);
    //设置滑动条最大值
    _slider.maximumValue=360;
    //设置滑动条的最小值，可以为负值
    _slider.minimumValue=0;
    //设置滑动条的滑块位置float值
    _slider.value=0;
    //左侧滑条背景颜色
    _slider.minimumTrackTintColor=[UIColor whiteColor];
    //右侧滑条背景颜色
    _slider.maximumTrackTintColor=[UIColor redColor];
    //设置滑块的颜色
    _slider.thumbTintColor=[UIColor orangeColor];
    //对滑动条添加事件函数
    [_slider addTarget:self action:@selector(pressSlider) forControlEvents:UIControlEventValueChanged];
    
    [self.mapView addSubview:_slider];
    
    //frontOverLay
    //创建滑动条对象(sideOverLay)
    _frontOverLay = [[UISlider alloc]init];
    //位置设置，高度不可变更，40写的不起作用，系统默认
    _frontOverLay.frame =CGRectMake(SCREEN_WIDTH - 350,160, 300, 40);
    //设置滑动条最大值
    _frontOverLay.maximumValue=100;
    //设置滑动条的最小值，可以为负值
    _frontOverLay.minimumValue=0;
    //设置滑动条的滑块位置float值
    _frontOverLay.value=50;
    //左侧滑条背景颜色
    _frontOverLay.minimumTrackTintColor=[UIColor whiteColor];
    //右侧滑条背景颜色
    _frontOverLay.maximumTrackTintColor=[UIColor redColor];
    //设置滑块的颜色
    _frontOverLay.thumbTintColor=[UIColor orangeColor];
    //对滑动条添加事件函数
    [_frontOverLay addTarget:self action:@selector(frontPressSlider) forControlEvents:UIControlEventValueChanged];
    
    [self.mapView addSubview:_frontOverLay];
    
}

/**
 *frontOverLay滑动事件
 */
- (void)frontPressSlider {
    NSString *rate = [NSString stringWithFormat:@"%.0f",_frontOverLay.value];
    [self.mapController reSetTakePhotoTime:rate];
}

- (void) pressSlider{
   [ToolHelper notifyError:[NSString stringWithFormat:@"value=%.0f",_slider.value]];
    NSString *angle = [NSString stringWithFormat:@"%.0f",_slider.value];
    //重置航线
    [self.mapView removeOverlays:self.mapView.overlays];
    [self.mapController cleanAllPointsWithMapView:self.mapView];
    //绘制多边形
    [self.mapView addOverlays:self.polygons];
    [self.mapController reSetAirCraftLine:angle FlyHeight:_setFlyHeightTextField.text];
}



#pragma mark - DJIWaypointConfigViewControllerDelegate Methods
- (void)cancelBtnActionInDJIWaypointConfigViewController:(DJIWaypointConfigViewController *)waypointConfigVC
{
    WeakRef(weakSelf);
    
    [UIView animateWithDuration:0.25 animations:^{
        WeakReturn(weakSelf);
        weakSelf.waypointConfigVC.view.alpha = 0;
    }];
}

-(void) initUI
{
    self.modeLabel.text = @"N/A";
    self.gpsLabel.text = @"0";
    self.vsLabel.text = @"0.0 M/S";
    self.hsLabel.text = @"0.0 M/S";
    self.altitudeLabel.text = @"飞行高度:0 M";
    
    //飞行检查
    UIButton *checkBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 100, 80, 50)];
    [checkBtn setTitle:@"飞行检查" forState:0];
    checkBtn.backgroundColor = [UIColor blackColor];
    [checkBtn setTitleColor:[UIColor whiteColor] forState:0];
    [checkBtn addTarget:self action:@selector(checkAirCraftStatues:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.mapView addSubview:checkBtn];

    
    //修改飞行高度
    _setFlyHeightTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, checkBtn.frame.origin.y + checkBtn.frame.size.height + 10, checkBtn.frame.size.width, checkBtn.frame.size.height)];
    _setFlyHeightTextField.text = @"50";
    [STANDARD_USER_DEFAULTS setObject:_setFlyHeightTextField.text forKey:@"airCraftHeight"];
    _setFlyHeightTextField.textAlignment = NSTextAlignmentCenter;
    _setFlyHeightTextField.backgroundColor = [UIColor blackColor];
    _setFlyHeightTextField.textColor = [UIColor whiteColor];
    _setFlyHeightTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    _setFlyHeightTextField.delegate = self;
    [self.mapView addSubview:_setFlyHeightTextField];
}

 /**
  *动态修改无人机高度
  */

- (void)textFieldDidEndEditing:(UITextField *)textField {
        [ToolHelper notifyError:[NSString stringWithFormat:@"%@",textField.text]];
    //存储
    NSString *heightStr = textField.text;
    [STANDARD_USER_DEFAULTS setObject:heightStr forKey:@"airCraftHeight"];
    [_setFlyHeightTextField endEditing:YES];
}

- (void)checkAirCraftStatues:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (!self.checkListVC) {
        self.checkListVC = [[DULPreflightChecklistController alloc] init];
        [self addChildViewController:self.checkListVC];
        _statusBarContainingView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH -SCREEN_WIDTH/3, 100, SCREEN_WIDTH/3, SCREEN_HEIGHT/4)];
        _statusBarContainingView.backgroundColor = [UIColor whiteColor];
        [self.mapView addSubview:_statusBarContainingView];
        self.checkListVC.view.frame = CGRectMake(0, 0, _statusBarContainingView.frame.size.width, _statusBarContainingView.frame.size.height);
        [_statusBarContainingView addSubview:self.checkListVC.view];

    }
   
    if (sender.selected) {
        _statusBarContainingView.alpha = 1;
    }else {
        _statusBarContainingView.alpha = 0;
    }
}

-(void)initData
{
    self.userLocation = kCLLocationCoordinate2DInvalid;
    self.droneLocation = kCLLocationCoordinate2DInvalid;
    
    self.mapController = [[DJIMapController alloc] init];
    self.tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addWaypoints:)];
    [self.mapView addGestureRecognizer:self.tapGesture];
}

#pragma mark DJISDKManagerDelegate Methods
- (void)appRegisteredWithError:(NSError *)error
{
    if (error){
        NSString *registerResult = [NSString stringWithFormat:@"Registration Error:%@", error.description];
        [ToolHelper notifyError:[NSString stringWithFormat:@"Registration Result-----%@",registerResult]];
    }
    else{
        [ToolHelper notifyError:@"注册成功"];
        
        DJIFlightController* flightController = [DemoUtility fetchFlightController];
        if (flightController) {
            flightController.delegate = self;
        }
        
        [DJISDKManager startConnectionToProduct];
    }
}

- (void)productConnected:(DJIBaseProduct *)product
{
//    if (product){
//         [ToolHelper notifyError:@"连接成功"];
//        DJIFlightController* flightController = [DemoUtility fetchFlightController];
//        if (flightController) {
//            flightController.delegate = self;
//        }
//    }else{
//      
//        [ToolHelper notifyError:@"Product disconnected"];
//    }
}

/**
 *编辑
 */
- (void)editBtnAction:(UIButton *)sender {
//    if (self.isEditingPoints) {
//        [self.mapController cleanAllPointsWithMapView:self.mapView];
//        [self.editBtn setTitle:@"编辑" forState:UIControlStateNormal];
//    }else
//    {
//        [self.editBtn setTitle:@"重置" forState:UIControlStateNormal];
//    }
    
    self.isEditingPoints = !self.isEditingPoints;
}

/**
 *userLocation 是用户的位置
 *droneLocation 是无人机的位置
 *聚焦
 */
- (void)focusMapAction:(UIButton *)sender {

    [ToolHelper notifyError:[NSString stringWithFormat:@"%f------%f",self.droneLocation.latitude,self.droneLocation.longitude]];

    
    if (self.droneLocation.latitude == 0) {
        if (CLLocationCoordinate2DIsValid(self.userLocation)) {
            MKCoordinateRegion region = {0};
            region.center = self.userLocation;
            region.span.latitudeDelta = 0.001;
            region.span.longitudeDelta = 0.001;
            
            [self.mapView setRegion:region animated:YES];
        }
    }else {
        if (CLLocationCoordinate2DIsValid(self.droneLocation)) {
            MKCoordinateRegion region = {0};
            region.center = self.droneLocation;
            region.span.latitudeDelta = 0.001;
            region.span.longitudeDelta = 0.001;
            
            [self.mapView setRegion:region animated:YES];
        }
    }
}

- (BOOL)prefersStatusBarHidden {
    return NO;
}
#pragma mark CLLocation Methods
- (void) startUpdateLocation
{
    if ([CLLocationManager locationServicesEnabled]) {
        if (self.locationManager == nil) {
            self.locationManager = [[CLLocationManager alloc] init];
            self.locationManager.delegate = self;
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            self.locationManager.distanceFilter = 0.1;
            if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                [self.locationManager requestAlwaysAuthorization];
            }
            [self.locationManager startUpdatingLocation];
        }
    }else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Location Service is not available" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
}

#pragma mark MKMapViewDelegate Method
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    
    if ([annotation isKindOfClass:[MKPointAnnotation class]]) {
        MKPinAnnotationView* pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"Pin_Annotation"];
        pinView.pinColor = MKPinAnnotationColorPurple;
        return pinView;
        
    }else if ([annotation isKindOfClass:[DJIAircraftAnnotation class]])
    {
        DJIAircraftAnnotationView* annoView = [[DJIAircraftAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"Aircraft_Annotation"];
        ((DJIAircraftAnnotation*)annotation).annotationView = annoView;
        return annoView;
    }
    
    return nil;
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation* location = [locations lastObject];
    self.userLocation = location.coordinate;
}

#pragma mark Custom Methods
- (void)addWaypoints:(UITapGestureRecognizer *)tapGesture
{
    CGPoint point = [tapGesture locationInView:self.mapView];
    
    if(tapGesture.state == UIGestureRecognizerStateEnded){
        if (self.isEditingPoints) {
            [self.mapController addPoint:point withMapView:self.mapView];
        }
    }
}

#pragma mark DJIFlightControllerDelegate
- (void)flightController:(DJIFlightController *)fc didUpdateState:(DJIFlightControllerState *)state
{
//    [ToolHelper notifyError:[NSString stringWithFormat:@"%f-----%f", state.aircraftLocation.coordinate.latitude, state.aircraftLocation.coordinate.longitude]];
        self.droneLocation = state.aircraftLocation.coordinate;
//    if (self.droneLocation.latitude == 0 && self.droneLocation.longitude == 0) {
//        self.droneLocation = self.userLocation;
//    }

    self.modeLabel.text = state.flightModeString;
    self.gpsLabel.text = [NSString stringWithFormat:@"%lu", (unsigned long)state.satelliteCount];
    self.vsLabel.text = [NSString stringWithFormat:@"%0.1f M/S",state.velocityZ];
    self.hsLabel.text = [NSString stringWithFormat:@"%0.1f M/S",(sqrtf(state.velocityX*state.velocityX + state.velocityY*state.velocityY))];
    self.altitudeLabel.text = [NSString stringWithFormat:@"%0.1f M",state.altitude];
    
    [self.mapController updateAircraftLocation:self.droneLocation withMapView:self.mapView];
    double radianYaw = RADIAN(state.attitude.yaw);
    [self.mapController updateAircraftHeading:radianYaw];
}

/**
 *返回
 */
- (void)back {
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)focusMap
{
    if (self.droneLocation.latitude == 0) {
        if (CLLocationCoordinate2DIsValid(self.userLocation)) {
            MKCoordinateRegion region = {0};
            region.center = self.userLocation;
            region.span.latitudeDelta = 0.001;
            region.span.longitudeDelta = 0.001;
            
            [self.mapView setRegion:region animated:YES];
        }
    }else {
        if (CLLocationCoordinate2DIsValid(self.droneLocation)) {
            MKCoordinateRegion region = {0};
            region.center = self.droneLocation;
            region.span.latitudeDelta = 0.001;
            region.span.longitudeDelta = 0.001;
            
            [self.mapView setRegion:region animated:YES];
        }
    }
    

}

- (void)addBtn:(UIButton *)button withActionInGSButtonVC:(DJIGSButtonViewController *)GSBtnVC {
    if (self.isEditingPoints) {
        self.isEditingPoints = NO;
        [button setTitle:@"add" forState:UIControlStateNormal];
    }else
    {
        self.isEditingPoints = YES;
        [button setTitle:@"finish" forState:UIControlStateNormal];
    }
}

- (void)clearBtnActionInGSButtonVC:(DJIGSButtonViewController *)GSBtnVC {
    [self.mapView removeOverlays:self.mapView.overlays];
    [self.mapController cleanAllPointsWithMapView:self.mapView];
}

- (void)focusMapBtnActionInGSButtonVC:(DJIGSButtonViewController *)GSBtnVC
{
    [self focusMap];
}

- (void)configBtnActionInGSButtonVC:(DJIGSButtonViewController *)GSBtnVC {
    WeakRef(weakSelf);
    NSMutableArray *arr = [NSMutableArray array];
    NSMutableArray *paramsArr = [NSMutableArray array];
    CLLocationCoordinate2D coordinates[self.mapController.latArr.count];
    //NSLog(@"%@----%@",self.mapController.latArr,self.mapController.lngArr);
    for (int i = 0; i < self.mapController.latArr.count; i ++) {
        coordinates[i].latitude = [self.mapController.latArr[i] doubleValue];
        coordinates[i].longitude = [self.mapController.lngArr[i] doubleValue];
    }

    MKPolygon *polygon = [MKPolygon polygonWithCoordinates:coordinates count:self.mapController.latArr.count];
    [arr addObject:polygon];
    self.polygons = [NSArray arrayWithArray:arr];
    //绘制多边形
    [self.mapView addOverlays:self.polygons];
    //绘制航线
    [self.mapController drawFlyDoneLine];
    
    //航线的节点数据
    NSMutableArray *pointsArr = [NSMutableArray array];
    self.mapController.airCraftLineBlock = ^(NSString *str) {//节点数据
        NSLog(@"节点数据-----%@",str);
        [pointsArr removeAllObjects];
        char *char_content = [str cStringUsingEncoding:NSASCIIStringEncoding];
        NSString *str1 = [[NSString alloc] initWithCString:char_content encoding:NSUTF8StringEncoding];
    
        NSDictionary *dic = [ToolHelper dictionaryWithJsonString:str1];
        NSLog(@"jsondic----%@",dic);
    
        NSArray *dataArr = [LinePointsModel mj_objectArrayWithKeyValuesArray:dic];
        
        for (LinePointsModel *model in dataArr) {
            CLLocation *location = [[CLLocation alloc] initWithLatitude:[model.lat floatValue] longitude:[model.lng floatValue]];
            [paramsArr addObject:location];
            [pointsArr addObject:model];
        }
     
        [weakSelf drawLinePoints:pointsArr];
        [weakSelf flayParamsSet:paramsArr];
        
        //拿到总路线长度，传给地图控制器，当飞行器到达开始点，根据高度等距离拍照

        for (int i = 0; i < dataArr.count; i ++) {
            LinePointsModel *modelS = dataArr[i];
            LinePointsModel *modelE = dataArr[i+1];
            MKMapPoint point1 = MKMapPointForCoordinate(CLLocationCoordinate2DMake([modelS.lat floatValue],[modelS.lng floatValue]));
            
            MKMapPoint point2 = MKMapPointForCoordinate(CLLocationCoordinate2DMake([modelE.lat floatValue], [modelE.lng floatValue]));
            CLLocationDistance distance = MKMetersBetweenMapPoints(point1, point2);
            CGFloat dis = distance;
            weakSelf.totalLineDistance += dis;
            
             //NSLog(@"总路线长度 ----%f",weakSelf.totalLineDistance);
            //[ToolHelper notifyError:[NSString stringWithFormat:@"总路线长度 ----%f",weakSelf.totalLineDistance]];

            if (i == dataArr.count -2) {
//                [ToolHelper notifyError:[NSString stringWithFormat:@"i---%d----%lu",i,(unsigned long)dataArr.count]];
                  [weakSelf setFlyTotalDis:weakSelf.totalLineDistance];
            }
        }
    };
}

/**
 *设置飞行总距离
 */
- (void)setFlyTotalDis:(CGFloat )dis {
    [self.mapController setTotalLineDistance: self.totalLineDistance];
}
/**
 *飞行参数设置
 */

- (void)flayParamsSet:(NSMutableArray *)arr {
    @WeakObj(self);
    
    //传值
     CLLocation* locationS = [arr objectAtIndex:0];
     CLLocation* locationE = [arr objectAtIndex:arr.count - 1];

    [self.mapController setLineStartCLLocation:locationS EndCLLocation:locationE];
    
  
    self.mapController.editPoints = arr;
    NSArray* wayPoints = self.mapController.editPoints;
   // NSLog(@"editArr---%@      arr----%@",self.mapController.editPoints,wayPoints);
    
    if (wayPoints == nil || wayPoints.count < 2)
    { //DJIWaypointMissionMinimumWaypointCount is 2.
        ShowMessage(@"No or not enough waypoints for mission", @"", nil, @"OK");
        return;
    }
    
    [UIView animateWithDuration:0.25 animations:^{
   
        selfWeak.waypointConfigVC.view.alpha = 1.f;

    }];
    
    if (self.waypointMission){
        [self.waypointMission removeAllWaypoints];
    }
    else{
        self.waypointMission = [[DJIMutableWaypointMission alloc] init];
    }
    
    for (int i = 0; i < wayPoints.count; i++) {
        CLLocation* location = [wayPoints objectAtIndex:i];
        if (CLLocationCoordinate2DIsValid(location.coordinate)) {
            DJIWaypoint* waypoint = [[DJIWaypoint alloc] initWithCoordinate:location.coordinate];
            [self.waypointMission addWaypoint:waypoint];
        }
    }
}

/**
 *画航线
 */
- (void)drawLinePoints:(NSArray *)arr {
    
    if(self.flyPointsDataArr.count > 0) {
        [self.flyPointsDataArr removeAllObjects];
    }

    CLLocationCoordinate2D line1Points[arr.count];
    
    for (int i = 0; i < arr.count; i ++) {
        LinePointsModel *model = arr[i];
        line1Points[i].latitude = [model.lat floatValue];
        line1Points[i].longitude = [model.lng floatValue];
//        NSLog(@"lat ---%f    lng----%f",line1Points[i].latitude,line1Points[i].longitude);
//
    }
    MKPolyline *line = [MKPolyline polylineWithCoordinates:line1Points count:arr.count];
    [self.flyPointsDataArr addObject:line];
    [self.mapView addOverlays:self.flyPointsDataArr];
}

#pragma mark - MAMapViewDelegate
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay {
    if ([overlay isKindOfClass:[MKPolygon class]])
    {
        MKPolygonRenderer *polygonRenderer = [[MKPolygonRenderer alloc] initWithPolygon:overlay];
        polygonRenderer.lineWidth   = 3.f;
        polygonRenderer.strokeColor = [UIColor colorWithRed:0 green:1 blue:0 alpha:0.5];
        polygonRenderer.fillColor   = [[UIColor redColor]colorWithAlphaComponent:0.5];
        
        return polygonRenderer;
    }
    
    if ([overlay isKindOfClass:[MKPolyline class]])
    {
        MKPolylineRenderer *polylineRenderer = [[MKPolylineRenderer alloc] initWithPolyline:overlay];
        polylineRenderer.strokeColor = [UIColor greenColor];
        polylineRenderer.lineWidth   = 5.f;
        
        NSInteger index = [self.lines indexOfObject:overlay];
        if(index == 0) {
            polylineRenderer.lineCap = kCGLineCapSquare;
            polylineRenderer.lineDashPhase = 0;
            polylineRenderer.lineDashPattern = @[@10, @10];
        } else {
            polylineRenderer.lineDashPhase = 0;
        }
        
        
        return polylineRenderer;
    }
    return nil;
}

#pragma mark action Methods

-(DJIWaypointMissionOperator *)missionOperator {
    return [DJISDKManager missionControl].waypointMissionOperator;
}

- (void)showAlertViewWithTitle:(NSString *)title withMessage:(NSString *)message
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)finishBtnActionInDJIWaypointConfigViewController:(DJIWaypointConfigViewController *)waypointConfigVC
{
    WeakRef(weakSelf);
    
    [UIView animateWithDuration:0.25 animations:^{
        WeakReturn(weakSelf);
        weakSelf.waypointConfigVC.view.alpha = 0;
    }];
    
    for (int i = 0; i < self.waypointMission.waypointCount; i++) {
        DJIWaypoint* waypoint = [self.waypointMission waypointAtIndex:i];
//        waypoint.altitude = [self.waypointConfigVC.altitudeTextField.text floatValue];
        NSString *flyHeight = [STANDARD_USER_DEFAULTS objectForKey:@"airCraftHeight"];
        waypoint.altitude = [flyHeight floatValue];
    }
    
    self.waypointMission.maxFlightSpeed = [self.waypointConfigVC.maxFlightSpeedTextField.text floatValue];
    self.waypointMission.autoFlightSpeed = [self.waypointConfigVC.autoFlightSpeedTextField.text floatValue];
    self.waypointMission.headingMode = (DJIWaypointMissionHeadingMode)self.waypointConfigVC.headingSegmentedControl.selectedSegmentIndex;
    [self.waypointMission setFinishedAction:(DJIWaypointMissionFinishedAction)self.waypointConfigVC.actionSegmentedControl.selectedSegmentIndex];
    [[self missionOperator] loadMission:self.waypointMission];
    
    WeakRef(target);
    @WeakObj(self);
    [[self missionOperator] addListenerToFinished:self withQueue:dispatch_get_main_queue() andBlock:^(NSError * _Nullable error) {
        
        WeakReturn(target);
  
        if (error) {
            [target showAlertViewWithTitle:@"Mission Execution Failed" withMessage:[NSString stringWithFormat:@"%@", error.description]];
        }
        else {
            [target showAlertViewWithTitle:@"Mission Execution Finished" withMessage:nil];
            [selfWeak.mapController stopTakePhoto];
        }
    }];
    [[self missionOperator] uploadMissionWithCompletion:^(NSError * _Nullable error) {
        if (error){
            NSString* uploadError = [NSString stringWithFormat:@"Upload Mission failed:%@", error.description];
           // ShowMessage(@"", uploadError, nil, @"OK");
        }else {
           // ShowMessage(@"", @"Upload Mission Finished", nil, @"OK");
        }
    }];
}

- (void)startBtnActionInGSButtonVC:(DJIGSButtonViewController *)GSBtnVC {
    @WeakObj(self);
    
    [[self missionOperator] startMissionWithCompletion:^(NSError * _Nullable error) {
        if (error){
            ShowMessage(@"Start Mission Failed", error.description, nil, @"OK");
        }else
        {
            ShowMessage(@"", @"Mission Started", nil, @"OK");
            selfWeak.mapController.isFinishedSet = YES;
        }
    }];
}

- (void)stopBtnActionInGSButtonVC:(DJIGSButtonViewController *)GSBtnVC {
    [[self missionOperator] stopMissionWithCompletion:^(NSError * _Nullable error) {
        if (error){
            NSString* failedMessage = [NSString stringWithFormat:@"Stop Mission Failed: %@", error.description];
            ShowMessage(@"", failedMessage, nil, @"OK");
        }else
        {
            ShowMessage(@"", @"Stop Mission Finished", nil, @"OK");
        }
    }];
}

- (void)switchToMode:(DJIGSViewMode)mode inGSButtonVC:(DJIGSButtonViewController *)GSBtnVC {
    if (mode == DJIGSViewMode_EditMode) {
        [self focusMap];
    }
}

- (void)encodeWithCoder:(nonnull NSCoder *)aCoder {
    
}

- (void)traitCollectionDidChange:(nullable UITraitCollection *)previousTraitCollection {
    
}

- (void)preferredContentSizeDidChangeForChildContentContainer:(nonnull id<UIContentContainer>)container {
    
}

- (CGSize)sizeForChildContentContainer:(nonnull id<UIContentContainer>)container withParentContainerSize:(CGSize)parentSize {
    
    CGSize size = CGSizeMake(100, 100);
    return size;
}

- (void)systemLayoutFittingSizeDidChangeForChildContentContainer:(nonnull id<UIContentContainer>)container {
    
}

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(nonnull id<UIViewControllerTransitionCoordinator>)coordinator {
    
}

- (void)willTransitionToTraitCollection:(nonnull UITraitCollection *)newCollection withTransitionCoordinator:(nonnull id<UIViewControllerTransitionCoordinator>)coordinator {
    
}

- (void)didUpdateFocusInContext:(nonnull UIFocusUpdateContext *)context withAnimationCoordinator:(nonnull UIFocusAnimationCoordinator *)coordinator {
    
}

- (void)setNeedsFocusUpdate {
    
}

- (BOOL)shouldUpdateFocusInContext:(nonnull UIFocusUpdateContext *)context {
    
    return YES;
}

- (void)updateFocusIfNeeded {
    
}



@end
